using UnityEngine;
using UnityEngine.UI;
using TEngine;
using System.Collections.Generic;
using GameLogic.Localization;
using System;
using TMPro;

namespace GameLogic
{
	partial class WeaponListPanel
    {
        Action<int> m_OnWeaponSelected;

        public Action<int> OnWeaponSelected { get => m_OnWeaponSelected; set => m_OnWeaponSelected = value; }

        #region 

        protected override void RegisterEvent()
        {
            base.RegisterEvent();

            m_lScrollWeapon.SetSpawnPrefabPath(() => { return "Assets/AssetRaw/UI/ShipConfigUI/WeaponCardWidget.prefab"; });
            m_lScrollWeapon.SetRefreshFunc(OnWeaponScrollRefresh);
            m_lScrollWeapon.SetItemSelectedFunc(OnWeaponItemSelected);

        }

        public void Refresh(IList<LoopScrollViewItemData> data)
        {
            m_lScrollWeapon.UpdateData(data);
        }

        public void Selecte(int idx)
        {
            m_lScrollWeapon.SelectCell(idx);
        }
        #endregion


        #region UI回调
        void OnWeaponItemSelected(LoopScrollViewItemData data, LoopScrollViewItemView view)
        {
            var root = view.transform.Find("Root");
            var cc = root.FindChildComponent<ColorChanger>("m_imgBG");
            cc.ChangeToIndex(1);
            if(m_OnWeaponSelected != null)
                m_OnWeaponSelected.Invoke(view.Index);
        }
        void OnWeaponScrollRefresh(LoopScrollViewItemData data, LoopScrollViewItemView view)
        {
            var root = view.transform.Find("Root");
            var previewImg = root.FindChildComponent<UnityEngine.UI.Image>("m_imgPreview");
            var nameT = root.FindChildComponent<TextMeshProUGUI>("m_tmpName");
            var cc = root.FindChildComponent<ColorChanger>("m_imgBG");
            cc.ChangeToIndex(0);

            if (data.ID < 0)
            {
                previewImg.sprite = GameModule.Resource.LoadAsset<Sprite>("Assets/AssetRaw/UIRaw/Atlas/Common/UnloadIcon.png");
                nameT.text = LLocalizationManager.Instance.GetString("common_unload");
                return;
            }
            var weaponID = GameDataModule.Instance.GetWeaponID(data.ID);
            var weaponCfg = ConfigSystem.Instance.Tables.TbWeapon.GetOrDefault(weaponID);

            nameT.text = LLocalizationManager.Instance.GetString(weaponCfg.Name);
            try
            {
                previewImg.sprite = GameModule.Resource.LoadAsset<Sprite>(weaponCfg.SpritePath);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }
        #endregion
    }
}